// ****************************************************************************
//	Copyright (c) 2011 Daniel Watman
//	http://www.keycommander.net/
// ****************************************************************************
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//	
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//	
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.
// *********************************************************************
//	File:	SPI.c
//	Purpose:	Basic functions to communicate with MAX3420 over SPI
//	Author:	Daniel Watman
//	Created: 2011.02.28
//	Updated:	2011.02.28
//	Version:	0.1
//	Target:	Atmel AVR XMEGA 128A1
//	Compiler: AVR-GCC
// *********************************************************************
//	Changes:
//		0.1	* Initial version
// *********************************************************************
//	To do:
//		* 
// *********************************************************************

#include <avr/io.h>
#include "SPI.h"
#include "types.h"

u08 SPI_byte(u08 data) {
	SPIC.DATA = data;				// send byte 0x
	while (!(SPIC.STATUS & 0x80));	// wait
	return SPIC.DATA;	// clear flag by reading data
}

u08 SPI_RWreg(u08 reg, u08 data) {
	u08 tmp;

	PORTC.OUTCLR = 0x10;	// set SS low
	SPI_byte(reg);			// write register, action, ACKSTAT
	tmp = SPI_byte(data);	// read/write data
	PORTC.OUTSET = 0x10;	// set SS high

	return tmp;
}

void USB_readFIFO(u08 fifo, u08 *buf, u08 bytes) {
	u08 i;

	PORTC.OUTCLR = 0x10;	// set SS low

	SPI_byte(fifo);			// set register to read
	for (i=0;i<bytes;i++)
		buf[i] = SPI_byte(0);	// read data

	PORTC.OUTSET = 0x10;	// set SS high
}

void USB_writeFIFO(u08 fifo, u08 *buf, u08 bytes) {
	u08 i;

	PORTC.OUTCLR = 0x10;	// set SS low

	SPI_byte(fifo | 0x02);	// set register to write
	for (i=0;i<bytes;i++)
		SPI_byte(buf[i]);	// write data

	PORTC.OUTSET = 0x10;	// set SS high
}
